package reflect;

import java.lang.reflect.Constructor;
import java.util.Scanner;

public class ReflectDemo3 {
    public static void main(String[] args) {
        Person p=new Person("王五");
        System.out.println(p);
        try {
            /*
            Class cls = Class.forName("reflect.Person");
            //Constructor c=cls.getConstructor();//获取无参构造器
            Constructor c=cls.getConstructor(String.class);//获取有参构造器
            Object obj=c.newInstance("王五");//实例化对象 new Person("王五");
            System.out.println(obj);
            Constructor c2=cls.getConstructor(String.class,int.class);
            Object obj2=c.newInstance("王五",20);
            System.out.println(obj2);
            */
            Scanner scan=new Scanner(System.in);
            System.out.println("请输入类名：");
            String line=scan.nextLine();
            Class cls=Class.forName(line);
            Constructor c=cls.getConstructor(String.class);
            System.out.println("请输入姓名：");
            String line1=scan.nextLine();
            Object obj=c.newInstance(line1);
            System.out.println(obj);
            System.out.println("-----------------------");
            Constructor c1=cls.getConstructor(String.class,int.class);
            System.out.println("请输入姓名：");
            String line2=scan.nextLine();
            System.out.println("请输入年龄：");
            int line3=scan.nextInt();
            Object obj1=c1.newInstance(line2,line3);
            System.out.println(obj1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
